<template>
    <el-row justify="center" align="middle" :style="rowStyle">
        <div class="login-container">
            <el-card style="max-width: 480px;">
                <template #header>
                    <img src="@/assets/images/login-head.png" alt="登录头图" />
                </template>
                <div class="jump-link">
                    <el-link type="primary" @click="formChange">{{ formType ? '前往登录' : '注册账号' }}</el-link>
                </div>
                <el-form ref="loginFormRef" :model="formData" :rules="rules">
                    <el-form-item prop="userName">
                        <el-input v-model="formData.userName" placeholder="用户名" prefix-icon="UserFilled"></el-input>
                    </el-form-item>
                    <el-form-item prop="passWord">
                        <el-input v-model="formData.passWord" type="password" placeholder="密码" prefix-icon="Lock"></el-input>
                    </el-form-item>
                    <el-form-item prop="validCode">
                        <el-input v-if="formType" v-model="formData.validCode" placeholder="验证码" prefix-icon="Lock">
                            <template #append>
                                <span @click="getValidCode" style="cursor: pointer;">{{ validCodeData.textInfo }}</span>
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" style="width: 100%;" @click="submitForm(loginFormRef)">
                            {{ formType ? '注册账号' : '登录' }}
                        </el-button>
                    </el-form-item>
                </el-form>
            </el-card>
        </div>
    </el-row>
</template>

<script setup>
import { ref, reactive, computed, toRaw } from 'vue'
import bgImage from '@/assets/images/background.png'
import { getCode, register, login, userMenuPermission } from '@/api'
import { useRouter } from 'vue-router'
import { useMenuStore } from '@/store/menu'
 
const menuStore = useMenuStore()
const router = useRouter()
// 0登录页  1注册页
const formType = ref(0)
const formData = reactive({
    userName: '',
    passWord: '',
    validCode: ''
})
const loginFormRef = ref()
// 验证码
const validCodeData = reactive({
    textInfo: '获取验证码',
    time: 15
})
// 防止定时器重复创建
let flag = false
let timer = null

// 拿到动态路由列表
const routerList = computed(() => menuStore.routerList)

// 切换登录注册表单
const formChange = () => {
    formType.value = formType.value ? 0 : 1
}
// 表单校验
const rules = reactive({
    userName: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { pattern: /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/, message: '请输入正确的用户名', trigger: 'blur' }
    ],
    passWord: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { pattern: /^[a-zA-Z0-9_-]{4,16}$/, message: '请输入4-16位密码', trigger: 'blur' }
    ]
})

// 获取验证码
const getValidCode = () => {
    // 如果定时器已经创建，便不再重复创建
    if (flag) return 
    // 清除之前的定时器（如果有）
    if (timer) {
        clearInterval(timer)
        timer = null
    }
    // 手机号userName校验
    const phoneRule = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
    if (!formData.userName || !phoneRule.test(formData.userName)) {
        ElMessage({
            message: '请输入正确的手机号',
            type: 'warning',
        })
        return
    }
    
    timer = setInterval(() => {
        if (validCodeData.time <= 0) {
            // 倒计时结束，清除定时器，重置状态
            clearInterval(timer)
            timer = null
            flag = false
            validCodeData.time = 15
            validCodeData.textInfo = '获取验证码'
        } else {
            validCodeData.time--
            validCodeData.textInfo = `剩余${validCodeData.time}秒`
        }
    }, 1000)
    flag = true
    getCode({
        tel: formData.userName
    }).then(({ data }) => {
        if (data.code === 10000) {
            ElMessage.success('验证码已发送！')
        }
    })
}

// 表单提交
const submitForm = async (formEl) => {
    // 表单整体校验
    // form实例没拿到，直接return 
    if (!formEl) return
    // from实例拿到了，进行整体表单校验
    await formEl.validate((valid, fields) => {
        if (valid) {
            // 注册
            if (formType.value) {
                // 调用注册api
                register({
                    userName: formData.userName,
                    passWord: formData.passWord,
                    validCode: formData.validCode
                }).then(({ data }) => {
                    if (data.code === 10000) {
                        ElMessage.success('注册成功！')
                        // 注册成功之后跳到登录页面
                        formType.value = 0
                    }
                })
            } else {
                login({
                    userName: formData.userName,
                    passWord: formData.passWord,
                }).then(({ data }) => {
                    if (data.code === 10000) {
                        ElMessage.success('登陆成功！')
                        console.log(data)
                        // 将token和用户信息缓存到浏览器，进行路由跳转
                        localStorage.setItem('pz_token', data.data.token)
                        localStorage.setItem('pz_userInfo', JSON.stringify(data.data.userInfo))
                        userMenuPermission().then(({ data }) => {
                            menuStore.dynamicMenu(data.data)
                            console.log(routerList.value)
                            // 将响应式数据转换成普通数组对象数据
                            toRaw(routerList.value).forEach(route => {
                                router.addRoute('main', route)
                            })
                            router.push('/')
                        })
                    }
                })
            }
        } else {
            console.log('错误提交')
        }
    })
}

// 设置背景样式
const rowStyle = computed(() => ({
    height: '100vh',
    backgroundImage: `url(${bgImage})`,
    backgroundSize: 'cover',
    backgroundPosition: 'center'
}))
</script>

<style lang="less" scoped>
.login-container {
    :deep(.el-card__header) {
        background-color: rgb(175, 152, 177);
        padding: 0;
    }
    img {
        width: 100%; 
        height: auto; 
        max-width: 100%; 
        display: block;

    }
    .jump-link {
        text-align: right;
        margin-bottom: 10px;
    }
}
</style>